// API客户端类
class ApiClient {
    constructor() {
        this.baseUrl = 'http://10.1.200.169:6724/api';
        this.token = localStorage.getItem('authToken');
    }

    // 设置认证令牌
    setToken(token) {
        this.token = token;
        localStorage.setItem('authToken', token);
    }

    // 清除认证令牌
    clearToken() {
        this.token = null;
        localStorage.removeItem('authToken');
    }

    // 获取请求头
    getHeaders() {
        const headers = {
            'Content-Type': 'application/json'
        };
        
        if (this.token) {
            headers['Authorization'] = `Bearer ${this.token}`;
        }
        
        return headers;
    }

    // 通用请求方法
    async request(url, options = {}) {
        const config = {
            headers: this.getHeaders(),
            ...options
        };

        console.log('发送请求:', `${this.baseUrl}${url}`, config);

        try {
            console.log('发送请求到:', `${this.baseUrl}${url}`, '选项:', config);
            const response = await fetch(`${this.baseUrl}${url}`, config);
            console.log('收到响应:', response.status, response.statusText);
            
            console.log('响应状态:', response.status, response.statusText);
            console.log('响应头:', Object.fromEntries(response.headers.entries()));
            
            // 检查认证状态
            if (response.status === 401) {
                this.clearToken();
                throw new Error('认证失败，请重新登录');
            }

            // 检查响应状态
            if (!response.ok) {
                const errorText = await response.text();
                console.error('HTTP错误响应内容:', errorText);
                let errorData = {};
                try {
                    errorData = JSON.parse(errorText);
                } catch (e) {
                    console.error('无法解析错误响应为JSON:', e);
                }
                throw new Error(errorData.message || `HTTP error! status: ${response.status}, message: ${errorText}`);
            }

            // 获取响应内容类型
            const contentType = response.headers.get('content-type');
            console.log('Response content-type:', contentType);
            console.log('Response headers:', [...response.headers.entries()]);
            
            // 处理图片响应
            if (contentType && contentType.startsWith('image/')) {
                console.log('处理为图片blob');
                const blob = await response.blob();
                console.log('图片blob大小:', blob.size, '类型:', blob.type);
                return blob;
            }
            
            // 处理JSON响应
            if (contentType && contentType.includes('application/json')) {
                console.log('处理为JSON');
                const data = await response.json();
                console.log('Response data:', data);
                return data;
            }
            
            // 处理其他application类型
            if (contentType && contentType.startsWith('application/')) {
                console.log('处理为application blob');
                const blob = await response.blob();
                console.log('Application blob大小:', blob.size, '类型:', blob.type);
                return blob;
            }

            // 默认处理为文本
            console.log('处理为文本');
            const responseText = await response.text();
            console.log('文本内容长度:', responseText.length);
            
            // 尝试解析JSON
            if (responseText) {
                try {
                    return JSON.parse(responseText);
                } catch (e) {
                    console.error('无法解析响应为JSON:', e);
                    throw new Error('服务器返回了无效的JSON响应');
                }
            } else {
                console.warn('响应内容为空');
                return null;
            }
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 登录
    async login(username, password) {
        const response = await this.request('/Auth/login', {
            method: 'POST',
            body: JSON.stringify({ "Username": username, "Password": password })
        });
        
        if (response && response.token) {
            this.setToken(response.token);
        }
        
        return response;
    }

    // 获取所有退款申请
    async getAllRefunds() {
        return await this.request('/refund/get-all', {
            method: 'POST',
            body: JSON.stringify({})
        });
    }

    // 根据ID获取退款申请详情
    async getRefundById(id) {
        return await this.request('/refund/get-by-id', {
            method: 'POST',
            body: JSON.stringify({ Id: id })
        });
    }

    // 根据患者ID获取退款申请
    async getRefundsByPatientId(patientId) {
        return await this.request('/refund/get-by-patient', {
            method: 'POST',
            body: JSON.stringify({ PatientId: patientId })
        });
    }

    // 根据患者ID和日期范围获取退款申请
    async getRefundsByPatientIdAndDays(patientId, days) {
        return await this.request('/refund/get-by-patient-and-date-range', {
            method: 'POST',
            body: JSON.stringify({ PatientId: patientId, Days: days })
        });
    }

    // 审核退款申请
    async auditRefund(id, auditData) {
        return await this.request(`/refund/${id}/audit`, {
            method: 'PATCH',
            body: JSON.stringify(auditData)
        });
    }

    // 获取患者信息
    async getPatientInfo(patientId) {
        return await this.request('/patient/get-patient-info', {
            method: 'POST',
            body: JSON.stringify({ PatientId: patientId })
        });
    }

    // 根据文件ID下载文件
    async downloadFile(fileId) {
        return await this.request('/file/download', {
            method: 'POST',
            body: JSON.stringify({ FileId: fileId })
        });
    }

    // 获取文件
    async getFileByPath(path) {
        console.log('API getFileByPath 调用开始:', path);
        try {
            // 清理路径格式，确保使用正确的路径分隔符
            const cleanPath = path.replace(/\\/g, '/').replace(/^\/+/, '');
            console.log('清理后的路径:', cleanPath);
            
            const result = await this.request('/file/get-by-path', {
                method: 'POST',
                body: JSON.stringify({ Path: cleanPath })
            });
            console.log('API getFileByPath 返回结果:', result);
            console.log('返回结果类型:', typeof result, '是否为Blob:', result instanceof Blob);
            return result;
        } catch (error) {
            console.error('API getFileByPath 调用失败:', path, error);
            throw error;
        }
    }

    // 获取文件预览URL
    getFilePreviewUrl(filePath) {
        if (!this.token) {
            return null;
        }
        
        // 创建一个包含认证信息的URL
        const url = new URL(`${this.baseUrl}/file/get-by-path`);
        return url.toString();
    }

    // 获取数据字典
    async getDictByType(type) {
        return await this.request('/dict/get-by-type', {
            method: 'POST',
            body: JSON.stringify({ Type: type })
        });
    }

    // 根据字典ID获取数据字典
    async getDictByDictId(dictId) {
        return await this.request('/dict/get-by-dict-id', {
            method: 'POST',
            body: JSON.stringify({ DictId: dictId })
        });
    }

    // 创建字典项
    async createDict(dictData) {
        console.log('API createDict:', this.baseUrl + '/dict', dictData);
        return await this.request('/dict', {
            method: 'POST',
            body: JSON.stringify(dictData)
        });
    }

    // 更新字典项
    async updateDict(dictId, dictData) {
        console.log('API updateDict:', this.baseUrl + `/dict/${dictId}`, dictData);
        return await this.request(`/dict/${dictId}`, {
            method: 'PUT',
            body: JSON.stringify(dictData)
        });
    }

    // 删除字典项
    async deleteDict(dictId) {
        return await this.request(`/dict/${dictId}`, {
            method: 'DELETE'
        });
    }
    
    // 获取退款申请列表（支持分页和多条件查询）
    async getRefunds(params = {}) {
        // 构建统计查询请求参数
        const requestBody = {
            pageIndex: params.pageIndex || 1,
            pageSize: params.pageSize || 20
        };
        
        // 添加可选的查询条件
        if (params.patientId) {
            requestBody.patientId = params.patientId;
        }
        if (params.patientName) {
            requestBody.patientName = params.patientName;
        }
        if (params.auditStatus !== null && params.auditStatus !== undefined && params.auditStatus !== '') {
            requestBody.auditStatus = parseInt(params.auditStatus);
        }
        if (params.startDate) {
            requestBody.startDate = params.startDate;
        }
        if (params.endDate) {
            requestBody.endDate = params.endDate;
        }
        if (params.applicantType) {
            requestBody.applicantType = params.applicantType;
        }
        
        console.log('API getRefunds 查询参数:', requestBody);
        
        try {
            // 调用后端统计API
            const response = await this.request('/refund/statistics', {
                method: 'POST',
                body: JSON.stringify(requestBody)
            });
            
            console.log('API getRefunds 返回结果:', response);
            
            return {
                data: response.data || [],
                totalCount: response.totalCount || 0,
                pageIndex: response.pageIndex || 1,
                pageSize: response.pageSize || 20,
                summary: response.summary || {
                    totalApplications: 0,
                    approvedCount: 0,
                    rejectedCount: 0,
                    pendingCount: 0,
                    totalRefundAmount: 0,
                    approvedRefundAmount: 0
                }
            };
        } catch (error) {
            console.error('获取统计数据失败:', error);
            throw error;
        }
    }
}

// 创建全局API客户端实例
const apiClient = new ApiClient();